from models import db, UserAddress
from common.response import APIResponse

class UserAddressService:
    @staticmethod
    def get_address_by_id(address_id):
        address = UserAddress.query.filter_by(id=address_id).first()
        if not address:
            return APIResponse.not_found('Address not found')
        return APIResponse.success(address.to_dict())

    @staticmethod
    def get_addresses_by_user(user_id):
        addresses = UserAddress.query.filter_by(user_id=user_id).all()
        addressLis = [address.to_dict() for address in addresses]
        return APIResponse.success(data={'items':addressLis,'total':len(addressLis)})

    @staticmethod
    def create_address(data):
        # 验证必填字段
        required_fields = ['user_id', 'address_detail']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 检查是否设置了默认地址，如果是，则取消其他地址的默认状态
        is_default = data.get('is_default', False)
        if is_default:
            UserAddress.query.filter_by(user_id=data['user_id'], is_default=True).update({'is_default': False})

        # 创建新地址
        new_address = UserAddress(
            user_id=data['user_id'],
            address_detail=data['address_detail'],
            name=data.get('name', None),
            phone=data.get('phone', None),
            location=data.get('location', None),
            is_default=is_default
        )

        try:
            new_address.save()
            return APIResponse.success(new_address.to_dict(), 'Address created successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def update_address(address_id, data):
        address = UserAddress.query.filter_by(id=address_id).first()
        if not address:
            return APIResponse.not_found('Address not found')

        # 如果更新默认地址状态为True，则取消其他地址的默认状态
        if 'is_default' in data and data['is_default'] is True and not address.is_default:
            UserAddress.query.filter_by(user_id=address.user_id, is_default=True).update({'is_default': False})
            address.is_default = True
        elif 'is_default' in data and data['is_default'] is False:
            address.is_default = False

        # 更新地址详情
        if 'address_detail' in data:
            address.address_detail = data['address_detail']

        if 'name' in data:
            address.name = data['name']
        if 'phone' in data:
            address.phone = data['phone']
        if 'location' in data:
            address.location = data['location']

        try:
            address.save()
            return APIResponse.success(address.to_dict(), 'Address updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def delete_address(address_id):
        address = UserAddress.query.filter_by(id=address_id).first()
        if not address:
            return APIResponse.not_found('Address not found')

        try:
            address.delete()
            return APIResponse.success(None, 'Address deleted successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)